<template>
  <div class="course-edit-container">
    <!-- 返回箭头 -->
    <div class="header">
      <el-button 
        icon="arrow-left"
        @click="handleBack"
        class="back-button"
      ></el-button>
    </div>
    
    <!-- 表单区域 -->
    <el-form 
      :model="formData"
      ref="formRef"
      label-width="120px"
      class="course-form"
      :rules="rules"
    >
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="formData.courseName" placeholder="请输入课程名称" />
      </el-form-item>
      
      <el-form-item label="课程开始时间" prop="courseStartTime">
        <el-input v-model="formData.courseStartTime" placeholder="请选择课程开始时间" 
        type="date"
        value-format="yyyy-MM-dd"
        />

      </el-form-item>
      
      <el-form-item label="课程结束时间" prop="courseEndTime">
        <el-input v-model="formData.courseEndTime" placeholder="请选择课程结束时间" 
        type="date"
        value-format="yyyy-MM-dd" />
      </el-form-item>
      
    </el-form>
    
    <!-- 底部按钮 -->
    <div class="button-group">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as courseApi from '@/api/courseManage'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const isEditMode = ref(false)

// 表单验证规则 --- 要求课程结束时间不得早于课程开始时间

const rules = {
  courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  courseStartTime: [{ required: false, message: '请输入课程开始时间', trigger: 'blur' }],
  courseEndTime: [
    { required: false, message: '请输入课程结束时间', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.courseStartTime) {
          if (new Date(value) < new Date(formData.courseStartTime)) {
            callback(new Error('课程结束时间不得早于课程开始时间'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],

  // auditReason: [
  //   {
  //     required: (rule, value, callback) => {
  //       if (formData.auditStatus === 1 && !value) {
  //         callback(new Error('请输入审核原因'))
  //       } else {
  //         callback()
  //       }
  //     },
  //     trigger: 'blur'
  //   }
  // ]
}

// 表单数据
const formData = reactive({
  id: '',
  courseName: '',
  courseStartTime: '',
  courseEndTime: ''
})

// 获取课程数据
const getCourseData = async () => {
  const courseId = route.params.id
  isEditMode.value = courseId !== 'new'

  if (isEditMode.value) {
    try {
      const res = await courseApi.getCourseById(courseId)
      if (res.code === 200) {
        Object.assign(formData, res.data)
      }
    } catch (error) {
      ElMessage.error('获取课程数据失败')
      console.error('获取课程数据失败:', error)
    }
  } else {
    // 新增模式，重置表单
    Object.assign(formData, {
      id: '',
      courseName: '',
      courseStartTime: '',
      courseEndTime: ''
    })
  }
}

// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 取消按钮
const handleCancel = () => {
  router.go(-1)
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await courseApi.addOrUpdateCourse(formData)
        if (res.code === 200) {
          ElMessage.success(isEditMode.value ? '课程信息更新成功' : '课程信息添加成功')
          router.push('/courseManage/index')
        }
      } catch (error) {
        ElMessage.error('提交失败')
        console.error('提交表单失败:', error)
      }
    }
  })
}

// 监听审核状态变化
watch(
  () => formData.auditStatus,
  (newVal) => {
    if (newVal === 0) {
      formData.auditReason = ''
    }
  }
)

// 页面加载时获取数据
onMounted(() => {
  getCourseData()
})
</script>

<style scoped>
.course-edit-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.back-button {
  font-size: 18px;
}

.course-form {
  margin-bottom: 40px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>